package com.moli.iov.admin.web.interceptor;

import cn.hutool.http.HttpStatus;
import com.alibaba.fastjson.JSONObject;
import com.moli.iov.admin.constants.Constants;
import com.moli.iov.admin.service.IAuthenticationFacadeService;
import com.moli.iov.rest.GenericCode;
import com.moli.iov.rest.RestResponse;
import com.moli.iov.sys.constants.Constant;
import com.moli.iov.util.ResponseUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

/**
 * <p>
 * 鉴权拦截器
 * </p>
 *
 * @author zql
 * @since 2019/9/20 10:44
 */
@Slf4j
@Component
public class AuthInterceptor extends HandlerInterceptorAdapter {

  @Autowired
  private IAuthenticationFacadeService authenticationFacadeService;
  /**
   * 路径错误
   */
  private static final String URI_ERROR = "/error";


  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
      throws Exception {
    try {

      if(URI_ERROR.equals(request.getRequestURI())){
        log.info("鉴权拦截器 路径错误  uri:{} ", request.getRequestURI());
        ResponseUtils.returnJson(response, JSONObject.toJSONString(RestResponse.failure("访问路径错误")),
            HttpStatus.HTTP_OK);
        return false;
      }

      String account = (String)request.getAttribute(Constant.DEFAULT_REQUEST_PERMISSION);

      boolean isT= authenticationFacadeService.auth(request, account);

      if(!isT){

        log.info("鉴权拦截器 鉴权失败 account: {}, uri:{} ", account, request.getRequestURI());
        ResponseUtils.returnJson(response, JSONObject.toJSONString(RestResponse.failure("无权限")),
            HttpStatus.HTTP_OK);
        return false;
      }

      return true;
    }catch(Exception e){
      log.error("鉴权拦截器 异常", e);
      ResponseUtils.returnJson(response, JSONObject.toJSONString(RestResponse.failure(GenericCode.LOGOUT_NOTICE)), Constants.RESPONSE_STATUS);
      return false;
    }
  }


}
